package orderitem

import (
	"log"
	"net/http"

	"gitee.com/zoneaurora/shop/internal/common"
	"gitee.com/zoneaurora/shop/internal/dto"
	"gitee.com/zoneaurora/shop/internal/model"
	"github.com/gin-gonic/gin"
)

func AddOrderItem(c *gin.Context) {
  db := common.DB()

  // 解析请求参数
  var reqOrderItem model.OrderItem
  c.Bind(&reqOrderItem)

  var oldOrderItem model.OrderItem
  if db.Where("order_id = ? AND product_id = ?", reqOrderItem.OrderID,
      reqOrderItem.ProductID).First(&oldOrderItem).Error != nil {
    // 若无过往记录则新增
    if db.Create(&reqOrderItem).Error != nil {
      common.JSON(c, http.StatusInternalServerError, "添加失败", nil)
      return
    }
    common.JSON(c, http.StatusOK, "添加成功", nil)
    return
  }
  // 否则增加数量
  if db.Model(&oldOrderItem).Update("number",
      oldOrderItem.Number + reqOrderItem.Number).Error != nil {
      common.JSON(c, http.StatusInternalServerError, "添加失败", nil)
      return
  }
  common.JSON(c, http.StatusOK, "添加成功", nil)
}

func ChangeNumber(c *gin.Context) {
  db := common.DB()

  var request model.OrderItem
  c.Bind(&request)

  var orderItem model.OrderItem
  if db.First(&orderItem, request.ID).Update("number", request.Number).Error != nil {
    common.JSON(c, http.StatusInternalServerError, "更新失败", nil)
  }
  common.JSON(c, http.StatusOK, "更新成功", nil)
}

func RmoveByID(c *gin.Context) {
  db := common.DB()

  // 获取请求id
  id := c.Param("id")

  log.Println(id)
  if db.Unscoped().Delete(&model.OrderItem{}, id).Error != nil {
    common.JSON(c, http.StatusInternalServerError, "删除失败", nil)
    return
  }
  common.JSON(c, http.StatusOK, "删除成功", nil)
}

func GetOrderItems(c *gin.Context) {
  db := common.DB()
  orderID := c.DefaultQuery("order", "0")

  var respOrderItems []dto.OrderItemDto
  if db.Table("order_items").Where("order_id = ?", orderID).
      Select("order_items.id, products.name, order_items.price, order_items.number, products.img_url").
      Joins("JOIN products ON products.ID = order_items.product_id").
      Scan(&respOrderItems).Error != nil {
    common.JSON(c, http.StatusInternalServerError, "查询失败", nil)
    return
  }
  common.JSON(c, http.StatusOK, "查询成功", respOrderItems)
}
